package com.hljx.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hljx.config.exception.DataException;
import com.hljx.dto.SysUserDTO;
import com.hljx.dto.SysUserPageDTO;
import com.hljx.entity.SysAccountingUnit;
import com.hljx.entity.SysUser;
import com.hljx.mapper.sys.SysAccountingUnitMapper;
import com.hljx.mapper.sys.SysUserMapper;
import com.hljx.service.SysAccountingUnitService;
import com.hljx.service.SysRoleService;
import com.hljx.service.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hljx.utils.JwtTokenUtil;
import com.hljx.vo.SysMenuVO;
import com.hljx.vo.UserLoginVO;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author gx
 * @since 2023-09-25
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    SysRoleService sysRoleService;

    @Autowired
    private SysAccountingUnitMapper sysAccountingUnitService;

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public UserLoginVO login(String code, String passWord) {
        LambdaQueryWrapper<SysUser> sysUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysUserLambdaQueryWrapper.eq(SysUser::getCode, code);
        SysUser sysUser = baseMapper.selectOne(sysUserLambdaQueryWrapper);
        if (sysUser == null) {
            throw new DataException("用户不存在!",201);
        }
        //密码校验
        if (!passwordEncoder.matches(passWord, sysUser.getPassword())) {
            throw new DataException("密码错误!",201);
        }
        SysAccountingUnit sysAccountingUnit = sysAccountingUnitService.selectById(sysUser.getAccountingId());
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setUserId(sysUser.getId());
        userLoginVO.setUserCode(sysUser.getCode());
        userLoginVO.setUserName(sysUser.getName());
        userLoginVO.setRoleId(sysUser.getRoleId());
        userLoginVO.setRoleName(sysUser.getRoleName());
        userLoginVO.setAccountingCode(sysAccountingUnit.getCode());
        String token = jwtTokenUtil.generateToken(sysUser.getCode());
        userLoginVO.setToken(token);
        //查询用户的菜单权限
        List<SysMenuVO> sysMenuVOS = sysRoleService.selectSysMenuVO(sysUser.getRoleId());
        userLoginVO.setMenuVOList(sysMenuVOS);
        return userLoginVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveOrUpdateNew(SysUserDTO user) {
        long count = count(Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getCode, user.getCode())
                .ne(user.getId() != null, SysUser::getId, user.getId()));
        if(count>0){
            throw new DataException("工号重复",201);
        }
        if(user.getRoleId()==null){
            user.setRoleId(-1L);
            user.setRoleName("--");
        }
        SysUser sysUser = new SysUser();
        BeanUtil.copyProperties(user,sysUser);
        if(StringUtils.isNotBlank(user.getPassword())){
            sysUser.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        return saveOrUpdate(sysUser);
    }

    @Override
    public Boolean removeByIdNew(Long id) {
        return removeById(id);
    }

    @Override
    public Boolean resetPassword(Long id,String password) {
        SysUser sysUser = getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getId, id));
        sysUser.setPassword(passwordEncoder.encode(password));
        return updateById(sysUser);
    }

    @Override
    public Boolean updateUserStatus(Long userId, Integer status) {
        return update(new LambdaUpdateWrapper<SysUser>().eq(SysUser::getId,userId).set(SysUser::getStatus,status));
    }

    @Override
    public IPage<SysUser> listSysUser(SysUserPageDTO dto) {
        IPage page = page(dto.getPage(), new QueryWrapper<SysUser>().lambda().eq(StringUtils.isNotBlank(dto.getRoleId()),SysUser::getRoleId,dto.getRoleId()).and(StringUtils.isNotBlank(dto.getName()),(i->
                     i.like(SysUser::getName,dto.getName())
                     .or().like(SysUser::getCode,dto.getName())
                     .or().like(SysUser::getPhone,dto.getName()))));
        return page;
    }
}
